/*
 * GenerateController.java		1.00	2008. 01. 21
 *
 * Copyright (c) 2008 David.Kim(KJS). All Rights Reserved.
 * 
 * This software is the confidential and proprietary information
 * of David.Kim(KJS).  You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the license agreement
 * you entered into with David.Kim(KJS).
 */
package doit.gen.util;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import doit.framework.util.Config;
import doit.gen.domain.Column;


/**
 * <pre>
 * system      : 공통
 * menu        : 공통
 * source      : GenerateController.java
 * description : 테이블에 매핑 되는 Controller 생성
 * </pre> 
 * @version
 * <pre> 
 * 1.0	2008. 01. 21  leewan  최초 작성
 * 1.1	
 * </pre>
 */

@SuppressWarnings("unchecked")
public class GenerateController implements BaseGenerate {
	public void generate( Map input, String tableName, List columns) throws Exception {
		String packageName = (String) input.get("packageName");
		String systemDiv = (String) input.get("systemDiv");
		String basePath = Config.getString("doit.generator.path.base");
        String parentPath = basePath + "/" + packageName;
		String childPath = Config.getString("doit.generator.path.controller");
		String tableComment = columns.size() > 0 ? ((Column)columns.get(0)).getTableComments() : "";
		
		// 폴더 생성
		GeneratorUtil.makeDirectorys( basePath, packageName);
		
		// 폴더 생성
		GeneratorUtil.makeDirectorys( parentPath, childPath);

		// 클래스명 분석
		String className = GeneratorUtil.getClassName( tableName);
		
		// 내용 생성
		StringBuffer sb = new StringBuffer();
		
		// 라이선스 생성
		sb.append( GeneratorUtil.printLicense(className + "Controller"));
		
		// 패키지 생성
		sb.append( GeneratorUtil.printPackage(packageName + "." + childPath));
		
		// 임포트 생성
		sb.append( printImport(packageName, className));
		
		// 자바독 생성
		sb.append( GeneratorUtil.printJavaDoc(className + "Controller", systemDiv, tableComment, tableComment));
		
		// 클래스 시작
		sb.append( printClassStart(className));
		
		// 클래스
		sb.append( printClass(className, columns));
		
		// 클래스 끝
		sb.append( printClassEnd());
		
		// 파일 생성
		File file = GeneratorUtil.makeFile( parentPath + "/" + childPath + "/" + className + "Controller" + "." + "java");
		
		// 파일에 쓰기
		RandomAccessFile raf = new RandomAccessFile( file, "rw");
		GeneratorUtil.write( raf, sb.toString());
		
		// 파일 닫기
		raf.close();
	}

    public String printImport( String packageName, String className) {
        StringBuffer sb = new StringBuffer();
        
        sb.append("import java.util.HashMap;").append("\n");
        sb.append("import java.util.List;").append("\n");
        sb.append("import java.util.Map;").append("\n");
        sb.append("\n");
        sb.append("import javax.servlet.http.HttpServletRequest;").append("\n");
        sb.append("import javax.servlet.http.HttpServletResponse;").append("\n");
        sb.append("\n");
        sb.append("import org.springframework.beans.factory.annotation.Autowired;").append("\n");
        sb.append("import org.springframework.web.servlet.ModelAndView;").append("\n");
        sb.append("\n");
        sb.append("import doit.framework.controller.BaseController;").append("\n");
        sb.append("import doit.framework.util.PageGenerator;").append("\n");
        sb.append("\n");
        sb.append("import " + packageName + ".domain." + className + ";").append("\n");
        sb.append("import " + packageName + ".service." + className + "Service;").append("\n");
        sb.append("\n");
        
        return sb.toString();
    }	
	
	public String printClassStart( String className) {
		return "public class " + className + "Controller extends BaseController {\n";
	}
	
	public String printClass( String className, List columns) throws Exception {
		StringBuffer sb = new StringBuffer();
		
		sb.append( printService( className));
		sb.append( printAuth());
		
		sb.append( printInitMethod( className));
		sb.append( printPageListMethod( className));
		sb.append( printListMethod( className));
		sb.append( printViewMethod( className));
		sb.append( printInsertFormMethod( className));
		sb.append( printInsertMethod( className));
		sb.append( printUpdateFormMethod( className));
		sb.append( printUpdateMethod( className));
		sb.append( printDeleteMethod( className));
		sb.append( printDeleteAllMethod(className, columns));
		
		return sb.toString();
	}
	
	public String printClassEnd() {
		return "}\n";
	}
	
	public String printService( String className) throws Exception {
		StringBuffer sb = new StringBuffer();
		sb.append("    @Autowired\n");
		sb.append("    private " + className + "Service " + GeneratorUtil.getArgumentName( className)+"Service;\n\n");
		return sb.toString();
	}
	
	public String printAuth() throws Exception {
		StringBuffer sb = new StringBuffer();

		sb.append("    protected void auth( HttpServletRequest request, HttpServletResponse response) throws Exception {\n");
		sb.append("    }\n\n");	

		return sb.toString();
	}
	
	public String printInitMethod( String className) throws Exception {
		StringBuffer sb = new StringBuffer();

		sb.append("    /*\n");
		sb.append("    protected ModelAndView init( HttpServletRequest request, HttpServletResponse response) throws Exception {\n");
		sb.append("        ModelAndView modelAndView = super.init(request, response);\n");
		sb.append("        //\n");
		sb.append("        // Logic Append Area\n");
		sb.append("        // Example : modelAndView.getModel().put(key, value);\n");
		sb.append("        //\n");
		sb.append("        return modelAndView;\n");
		sb.append("    }\n");
		sb.append("    */\n\n");
		
		return sb.toString();
	}	
	
	public String printPageListMethod( String className) throws Exception {
		StringBuffer sb = new StringBuffer();

		sb.append("    public ModelAndView pageList( HttpServletRequest request, HttpServletResponse response) throws Exception {\n");
		sb.append("        Map input = new HashMap();\n");
		sb.append("        bind( request, input);\n");
		sb.append("\n");
		sb.append("        Map model = new PageGenerator().generate(request, input,  " + GeneratorUtil.getArgumentName( className) + "Service.get" + className +  "PageList( input));\n");
		sb.append("\n");
		sb.append("        return new ModelAndView( getPageList(), model);\n");
		sb.append("    }\n\n");	

		return sb.toString();
	}	
	
	public String printListMethod( String className) throws Exception {
		StringBuffer sb = new StringBuffer();

		sb.append("    public ModelAndView list( HttpServletRequest request, HttpServletResponse response) throws Exception {\n");
		sb.append("        Map input = new HashMap();\n");
		sb.append("        bind( request, input);\n");
		sb.append("\n");
		sb.append("        List output = " + GeneratorUtil.getArgumentName( className) + "Service.get" + className +  "List( input);\n");
		sb.append("\n");
		sb.append("        Map model = new HashMap();\n");
		sb.append("        model.put( \"output\", output);\n");
		sb.append("\n");
		sb.append("        return new ModelAndView( getList(), model);\n");
		sb.append("    }\n\n");	

		return sb.toString();
	}
	
	public String printViewMethod( String className) throws Exception {
		StringBuffer sb = new StringBuffer();

		sb.append("    public ModelAndView view( HttpServletRequest request, HttpServletResponse response) throws Exception {\n");
		sb.append("        Map input = new HashMap();\n");
        sb.append("        bind( request, input);\n");
        sb.append("\n");
		sb.append("        Map output = " + GeneratorUtil.getArgumentName( className) + "Service.get" + className +  "( input);\n");
		sb.append("\n");
		sb.append("        Map model = new HashMap();\n");
		sb.append("        model.put( \"output\", output);\n");
		sb.append("\n");
		sb.append("        return new ModelAndView( getView(), model);\n");
		sb.append("    }\n\n");	

		return sb.toString();
	}
	
	public String printInsertFormMethod( String className) throws Exception {
		StringBuffer sb = new StringBuffer();

		sb.append("    public ModelAndView insertForm( HttpServletRequest request, HttpServletResponse response) throws Exception {\n");
		sb.append("        Map model = new HashMap();\n");
		sb.append("\n");
		sb.append("        return new ModelAndView( getInsertForm(), model);\n");
		sb.append("    }\n\n");	

		return sb.toString();
	}
	
	public String printInsertMethod( String className) throws Exception {
		StringBuffer sb = new StringBuffer();
		
		sb.append("    public ModelAndView insert( HttpServletRequest request, HttpServletResponse response) throws Exception {\n");
        sb.append("        " + className + " input = new " + className + "();\n");
        sb.append("        bind( request, input);\n");
        sb.append("\n");
		sb.append("        Object output = " + GeneratorUtil.getArgumentName( className) + "Service.insert" + className +  "( input);\n");
		sb.append("\n");
		sb.append("        Map model = new HashMap();\n");
		sb.append("        model.put( \"output\", output);\n");
		sb.append("\n");
		sb.append("        return new ModelAndView( getInsert(), model);\n");
		sb.append("    }\n\n");	

		return sb.toString();
	}
	
	public String printUpdateFormMethod( String className) throws Exception {
		StringBuffer sb = new StringBuffer();

		sb.append("    public ModelAndView updateForm( HttpServletRequest request, HttpServletResponse response) throws Exception {\n");
		sb.append("        Map input = new HashMap();\n");
        sb.append("        bind( request, input);\n");
        sb.append("\n");
		sb.append("        Map output = " + GeneratorUtil.getArgumentName( className) + "Service.get" + className +  "( input);\n");
		sb.append("\n");
		sb.append("        Map model = new HashMap();\n");
		sb.append("        model.put( \"output\", output);\n");
		sb.append("\n");
		sb.append("        return new ModelAndView( getUpdateForm(), model);\n");
		sb.append("    }\n\n");	

		return sb.toString();
	}
	
	public String printUpdateMethod( String className) throws Exception {
		StringBuffer sb = new StringBuffer();
		
		sb.append("    public ModelAndView update( HttpServletRequest request, HttpServletResponse response) throws Exception {\n");
		sb.append("        " + className + " input = new " + className + "();\n");
        sb.append("        bind( request, input);\n");
        sb.append("\n");
		sb.append("        int output = " + GeneratorUtil.getArgumentName( className) + "Service.update" + className +  "( input);\n");
		sb.append("\n");
		sb.append("        Map model = new HashMap();\n");
		sb.append("        model.put( \"output\", output);\n");
		sb.append("\n");
		sb.append("        return new ModelAndView( getUpdate(), model);\n");
		sb.append("    }\n\n");	

		return sb.toString();
	}
	
	public String printDeleteMethod( String className) throws Exception {
		StringBuffer sb = new StringBuffer();
		
		sb.append("    public ModelAndView delete( HttpServletRequest request, HttpServletResponse response) throws Exception {\n");
		sb.append("        " + className + " input = new " + className + "();\n");
        sb.append("        bind( request, input);\n");
        sb.append("\n");
		sb.append("        int output = " + GeneratorUtil.getArgumentName( className) + "Service.delete" + className +  "( input);\n");
		sb.append("\n");
		sb.append("        Map model = new HashMap();\n");
		sb.append("        model.put( \"output\", output);\n");
		sb.append("\n");
		sb.append("        return new ModelAndView( getDelete(), model);\n");
		sb.append("    }\n\n");	

		return sb.toString();
	}
	
	public String printDeleteAllMethod( String className, List columns) throws Exception {
		StringBuffer sb = new StringBuffer();

		List pkColumnList = new ArrayList();
		for( int i=0; i<columns.size(); i++)
			if( ((Column)columns.get( i)).getPrimaryYn().equals("Y"))
				pkColumnList.add( columns.get( i));
		
		String lastPrimaryColumnName = ((Column)pkColumnList.get( pkColumnList.size()-1)).getColumnName();		
		
		sb.append("    public ModelAndView deleteAll( HttpServletRequest request, HttpServletResponse response) throws Exception {\n");
		sb.append("        Map input = new HashMap();\n");
		sb.append("        bind( request, input);\n");
		sb.append("\n");
		sb.append("        int output = 0;\n");
		sb.append("        if (bindCheckBox(request, input, \""+GeneratorUtil.getFieldName( lastPrimaryColumnName)+"\", \"chk\"))\n");
		sb.append("            output = " + GeneratorUtil.getArgumentName( className) + "Service.delete" + className +  "All( input);\n");
		sb.append("\n");
		sb.append("        Map model = new HashMap();\n");
		sb.append("        model.put( \"output\", output);\n");
		sb.append("\n");
		sb.append("        return new ModelAndView( getDeleteAll(), model);\n");
		sb.append("    }\n\n");	

		return sb.toString();
	}
	
	public String printField( Column column) throws Exception {
		return "";
	}
}
